﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace PayloadTracker.APRS.Parsers
{
    class ParserProvider
    {
        public static ParserProvider Instance = new ParserProvider();
        List<IParser> m_Parsers;
        private ParserProvider()
        {
            m_Parsers = new List<IParser>();

            foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (t.IsAbstract)
                    continue;
                if (t.IsDefined(typeof(APRS.Parsers.ParserName), true))
                {
                    try
                    {
                        var controlattribute = t.GetCustomAttributes(typeof(APRS.Parsers.ParserName), true)[0] as APRS.Parsers.ParserName;
                        var aprsparser = Activator.CreateInstance(t, true) as APRS.Parsers.IParser;

                        m_Parsers.Add(aprsparser);

                    }
                    catch (System.Exception ex)
                    {
                        Logger.LOG.Error("Unable to load APRS Parser " + t.ToString() + " due to: " + ex.ToString());
                    }
                }
            }
        }

        public IParser GetParser(string data)
        {
            foreach (IParser parser in m_Parsers)
                if (parser.IsValidSentance(data))
                    return parser;

            return null;
        }
        public APRSBeacon AutoParse(string data)
        {
            var p = GetParser(data);
            return (p != null) ? p.Parse(data) : null;
        }

    }
}
